/**
 * AddressController
 *
 * @description :: Server-side logic for managing Addresses
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var addressObject = {
	reciveUser: "string",
	username: "string",
	mobile: "string",
	location: "string",
	lat: "string",
	lng: "string",
	address: "string"
};


module.exports = {
	


  /**
   * `AddressController.create()`
   */
  create: function (req, res) {

		var params = req.params.all();

		var username = params.username;
		var token = params.token;
		var reciveUser = params.reciveUser;
		var mobile = params.mobile;
		var location = params.location;
		var lat = params.lat;
		var lng = params.lng;
		var address = params.address;

		var error = [];

		for(var i in addressObject) {
			var p = params[i];

			if( typeof p !== addressObject[i]  ){
				error.push(i);
			}

		}

		if(username==undefined) {
			error.push("username");
		}

		if(token==undefined) {
			errpr.push("token");
		}


		if(error.length > 0)
			return res.json(error);

		var address = {
			recive_user: reciveUser,
			mobile: mobile,
			location: location,
			lat: lat,
			lng: lng,
			address: address
		};


		AuthenService.fromToken(username, token, function(user){
		
			if(user == null) {
				return res.json({
					code: -1,
					message: "认证失败"
				});
			}

			address.owner = user;

			Address.create(address).exec(function(err, created){

				if(err){
					return res.json({
						code: -1,
						message: "系统错误"
					});
				}else{
					return res.json({
						code: 0,
						data: created
					});
				}
			});	

		});


  },


  /**
   * `AddressController.get()`
   */
  get: function (req, res) {


		var params = req.allParams();
		
		var username = params.username;
		var token = params.token;
		var id = params.id;

		AuthenService.fromToken(username, token, function(user){
		
			if(user == null) {
				return res.json({
					code: -1,
					message: "认证失败"
				});
			}


			Address.findOne({
				id:id,
				owner: user.id
			})
			.exec(function(err, address){

				if(err || address == null) {

					return res.json({
						code: 0,
						message: "该地址不存在或已经被删除"
					});
				}

				return res.json({
					code: 1,
					address: address
				});

			});

		});

/*

		var id = parseInt(params.id);

		if(id == undefined | id == NaN){
			return res.json({
				code: -1,
				message: "请传入正确参数"
			});
		}

		Address.find({
			where: {id:id}
		}).exec(function(err, address){
			
			var returnObj = {};

			if(err) {
				returnObj.code = -1;
				returnObj.message = "查询出错"
			}else {
				returnObj.code = 0;
				returnObj.data = address
			}

			return res.json(returnObj);

		})
*/

  },


  /**
   * `AddressController.update()`
   */
  update: function (req, res) {
    return res.json({
      todo: 'this is update'
    });
  },


  /**
   * `AddressController.delete()`
   */
  delete: function (req, res) {
    return res.json({
      todo: 'this is  delete'
    });
  }
};

